package com.suqiu.common.annotation;

import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.suqiu.common.exception.SuqiuServiceException;

import javax.validation.*;
import java.lang.annotation.*;
import java.lang.reflect.Method;

/**
 * @author: suqiu
 * @Date: 2022/3/25 13:52
 * @Description: 自定义手机号码注解校验器
 */
@Documented
@Constraint(validatedBy = NotPhone.PhoneValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotPhone {
    String message() default "手机格式不正确!";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class PhoneValidator implements ConstraintValidator<NotPhone, String> {

        private static final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();

        @Override
        public boolean isValid(String phoneNum, ConstraintValidatorContext constraintValidatorContext) {
            // 不以 +号 开头
            if (phoneNum != null && phoneNum.charAt(0) != '+') {
                constraintValidatorContext.disableDefaultConstraintViolation();
                constraintValidatorContext.buildConstraintViolationWithTemplate("请以 +国家编号 开头").addConstraintViolation();
                return false;
            }
            Phonenumber.PhoneNumber number = null;
            try {
                number = phoneNumberUtil.parse(phoneNum, Phonenumber.PhoneNumber.CountryCodeSource.UNSPECIFIED.name());
            } catch (NumberParseException e) {
                return false;
            }
            return phoneNumberUtil.isValidNumber(number);

        }

        @Override
        public void initialize(NotPhone constraintAnnotation) {
        }
    }

}